package com.example.musicplayer;

import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.provider.ContactsContract;
import android.service.controls.actions.CommandAction;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
public class MusicService extends Service{

        //控制命令
        public static final int COMMAND_UNKNOWN = -1;
        public static final int COMMAND_PLAY = 0;
        public static final int COMMAND_PAUSE = 1;
        public static final int COMMAND_STOP = 2;
        public static final int COMMAND_RESUME = 3;
        public static final int COMMAND_PREVIOUS = 4;
        public static final int COMMAND_NEXT = 5;
        public static final int COMMAND_CHECK_IS_PLAYING = 6;
        public static final int COMMAND_SEEK_TO = 7;
        public static final int COMMAND_MODE_CHANGE = 8;

        //播放状态
        public static final int STATUS_PLAYING = 0;
        public static final int STATUS_PAUSED = 1;
        public static final int STATUS_STOP = 2;
        public static final int STATUS_COMPLETED = 3;

        //广播控制类型
        public static final String BROADCAST_MUSICSERVICE_CONTROL = "MusicService.ACTION_CONTROL";
        public static final String BROADCAST_MUSICSERVICE_UPDATE_STATUS = "MusicService.ACTION_UPDATE";


        private boolean firstPlayCheck = true;
        private int number = 0;
        private int status;

        private int playMode = 0;

        private MediaPlayer player = new MediaPlayer();

        private CommandReceiver receiver;

        public int randomArray[];


        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();
            bindCommandReceiver();
            status = MusicService.STATUS_STOP;
        }

        @Override
        public void onDestroy() {
            if(player != null)
            {
                player.release();
            }
            super.onDestroy();
        }

        private void load(int number)
        {
            try {
                player.reset();
                player.setDataSource(MusicList.getMusicArrayList().get(number).getMusicPath());
                player.prepare();
            }catch (Exception e){
                e.printStackTrace();
            }

            player.setOnCompletionListener(completionListener);


        }

        MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                sendBroadcastOnStatusChanged(STATUS_COMPLETED);

            }
        };


        private void play(int number)
        {
            if(player !=null && player.isPlaying())
            {
                player.stop();
            }
            load(number);
            player.start();
            status = STATUS_PLAYING;
            sendBroadcastOnStatusChanged(STATUS_PLAYING);
        }


        private void pause()
        {
            if (player.isPlaying())
            {
                player.pause();
                status = STATUS_PAUSED;
                sendBroadcastOnStatusChanged(STATUS_PAUSED);
            }
        }

        private void stop()
        {
            player.stop();
            status = STATUS_STOP;
            sendBroadcastOnStatusChanged(STATUS_STOP);
        }

        private void resume()
        {
            player.start();
            status = STATUS_PLAYING;
            sendBroadcastOnStatusChanged(STATUS_PLAYING);
        }

        private void replay()
        {
            player.start();
            status = STATUS_PLAYING;
            sendBroadcastOnStatusChanged(STATUS_PLAYING);
        }

        private void seekTo(int time)
        {
            player.seekTo(time);
        }

        private void moveNumberToNext()
        {
            if(playMode == MainActivity.MODE_LISTCYCLE || playMode == MainActivity.MODE_SINGLECYCLE )
            {
                if(number == MusicList.getMusicArrayList().size()-1)
                {
                    number = 0;
                    play(number);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                } else
                {
                    ++number;
                    play(number);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                }
            }else if(playMode == MainActivity.MODE_LISTSINGLE)
            {
                if(number == MusicList.getMusicArrayList().size()-1)
                {
                    //stop();
                    //status = STATUS_STOP;
                    Toast.makeText(getApplicationContext(),R.string.tip_reach_bottom,Toast.LENGTH_SHORT).show();
                    //sendBroadcastOnStatusChanged(STATUS_STOP);
                } else
                {
                    ++number;
                    play(number);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                }
            }
            else if(playMode == MainActivity.MODE_RAMDOM)
            {
                firstPlayCheck = false;
                //Toast.makeText(getApplicationContext(),"1",Toast.LENGTH_SHORT).show();
                if(number == MusicList.getMusicArrayList().size()-1)
                {
                    number = 0;
                    play(randomArray[number]);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                } else
                {
                    ++number;
                    play(randomArray[number]);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                }
            }

        }

        private void moveNumberToPrevious()
        {
            if(playMode == MainActivity.MODE_LISTCYCLE || playMode == MainActivity.MODE_SINGLECYCLE )
            {
                if(number == 0)
                {
                    number = MusicList.getMusicArrayList().size()-1;
                    play(number);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                } else
                {
                    --number;
                    play(number);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                }

            }else if(playMode == MainActivity.MODE_LISTSINGLE)
            {
                if(number == 0)
                {
                    //stop();
                    //status = STATUS_STOP;
                    Toast.makeText(getApplicationContext(),R.string.tip_reach_top,Toast.LENGTH_SHORT).show();
                    //sendBroadcastOnStatusChanged(STATUS_STOP);
                } else
                {
                    --number;
                    play(number);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                }
            }
            else if(playMode == MainActivity.MODE_RAMDOM)
            {
                firstPlayCheck = false;
                //Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
                if(number == 0)
                {
                    number = MusicList.getMusicArrayList().size()-1;
                    play(randomArray[number]);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                } else
                {
                    --number;
                    play(randomArray[number]);
                    status = STATUS_PLAYING;
                    sendBroadcastOnStatusChanged(STATUS_PLAYING);
                }
            }
        }


        private void sendBroadcastOnStatusChanged(int status)
        {
            Intent intent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
            intent.putExtra("status",status);

            if(playMode == MainActivity.MODE_RAMDOM)
            {

                if(status != STATUS_STOP)
                {
                    intent.putExtra("musicName",MusicList.getMusicArrayList().get(randomArray[number]).getMusicName());
                    intent.putExtra("musicArtist",MusicList.getMusicArrayList().get(randomArray[number]).getMusicArtist());
                    intent.putExtra("number",randomArray[number]);
                    intent.putExtra("time",player.getCurrentPosition());
                    intent.putExtra("duration",player.getDuration());
                    //Toast.makeText(getApplicationContext(),player.getDuration(),Toast.LENGTH_SHORT).show();
                }

            }
            else
            {
                if(status != STATUS_STOP)
                {
                    intent.putExtra("musicName",MusicList.getMusicArrayList().get(number).getMusicName());
                    intent.putExtra("musicArtist",MusicList.getMusicArrayList().get(number).getMusicArtist());
                    intent.putExtra("number",number);
                    intent.putExtra("time",player.getCurrentPosition());
                    intent.putExtra("duration",player.getDuration());
                    //Toast.makeText(getApplicationContext(),player.getDuration(),Toast.LENGTH_SHORT).show();
                }
            }



            sendBroadcast(intent);
        }




        class CommandReceiver extends BroadcastReceiver
        {

            @Override
            public void onReceive(Context context, Intent intent) {
                int command = intent.getIntExtra("command",COMMAND_UNKNOWN);

                switch (command)
                {
                    case COMMAND_PLAY:
                        number = intent.getIntExtra("number",0);
                        randomArray = intent.getIntArrayExtra("randomArray");
                        //firstPlayCheck = true;
                        if(playMode == MainActivity.MODE_RAMDOM)
                        {
                            number = getMusicPositionInRandom(number);
                            play(randomArray[number]);
                        }
                        else
                        {
                            play(number);
                        }

                        break;

                    case COMMAND_PAUSE:
                        pause();
                        break;

                    case COMMAND_STOP:
                        stop();
                        break;

                    case COMMAND_PREVIOUS:
                        moveNumberToPrevious();
                        break;

                    case COMMAND_NEXT:
                        moveNumberToNext();
                        break;

                    case COMMAND_RESUME:
                        resume();
                        break;

                    case COMMAND_CHECK_IS_PLAYING:
                        if (player != null && player.isPlaying())
                        {
                            status = STATUS_PLAYING;
                            sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
                        }
                        break;

                    case COMMAND_SEEK_TO:
                        seekTo(intent.getIntExtra("time",0));
                        break;

                    case COMMAND_UNKNOWN:
                        break;

                    case COMMAND_MODE_CHANGE:
                        playMode = intent.getIntExtra("playMode",0);
                        break;

                    default:
                        break;

                }


            }
        }

        private void bindCommandReceiver()
        {
            receiver = new CommandReceiver();
            IntentFilter filter = new IntentFilter(BROADCAST_MUSICSERVICE_CONTROL);
            registerReceiver(receiver,filter);

        }

        private int getMusicPositionInRandom(int number)
        {

            for (int i = 0;i<MusicList.getMusicArrayList().size();i++)
            {
                if(randomArray[i] == number)
                {
                    return i;
                }

            }
            return 0;

        }
    }
